# -*- coding: utf-8 -*-
"""
派生密钥管理模型
"""

from django.db import models
import uuid
import time
from datetime import datetime, timedelta

from apps.generate_secret.models import AppSecret


class DeriveKey(models.Model):
    """派生密钥模型"""
    
    ALGORITHM_CHOICES = [
        ('AES-128', 'AES-128'),
        ('AES-192', 'AES-192'),
        ('AES-256', 'AES-256'),
        ('DES', 'DES'),
        ('3DES', '3DES'),
    ]
    
    PURPOSE_CHOICES = [
        ('encryption', 'encryption'),
        ('decryption', 'decryption'),
        ('signing', 'signing'),
    ]
    
    STATUS_CHOICES = [
        ('active', 'active'),
        ('inactive', 'inactive'),
    ]
    
    id = models.AutoField(primary_key=True)
    app_id = models.ForeignKey(
        AppSecret,
        to_field='app_id',  # 指定关联字段
        on_delete=models.SET_NULL,
        null=True,                  # 必须设置 null=True
        blank=True, 
        db_column='app_id'  # 数据库中的列名（可选）
    )
    key_id = models.CharField(max_length=64, unique=True, verbose_name='密钥ID', db_index=True)
    algorithm = models.CharField(max_length=20, choices=ALGORITHM_CHOICES, verbose_name='加密算法')
    purpose = models.CharField(max_length=20, choices=PURPOSE_CHOICES, null=True, blank=True, verbose_name='密钥用途')
    description = models.TextField(null=True, blank=True, verbose_name='密钥描述')
    key = models.TextField(verbose_name='加密后的密钥')
    expiry_days = models.IntegerField(default=1, verbose_name='过期天数')
    derive_id = models.CharField(max_length=64, verbose_name='分散因子')
    root_key_id = models.CharField(max_length=64, verbose_name='根密钥ID', db_index=True)
    user_cert = models.TextField(verbose_name='用户公钥证书')
    status = models.CharField(max_length=20, choices=STATUS_CHOICES, default='active', verbose_name='状态')
    version = models.CharField(max_length=20, verbose_name='版本号')
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')
    expires_at = models.DateTimeField(verbose_name='过期时间')
    disabled_at = models.DateTimeField(null=True, blank=True, verbose_name='禁用时间')
    enabled_at = models.DateTimeField(null=True, blank=True, verbose_name='启用时间')
    create_by = models.CharField(max_length=64, default='system', verbose_name='创建者')
    update_by = models.CharField(max_length=64, default='system', verbose_name='更新者')
    is_delete = models.BooleanField(default=False, verbose_name='是否删除', db_index=True)
    
    class Meta:
        db_table = 'derive_key'
        verbose_name = '派生密钥'
        verbose_name_plural = '派生密钥'
    
    def __str__(self):
        return f"{self.key_id} - {self.algorithm}"
    
    @classmethod
    def generate_key_id(cls):
        """生成密钥ID"""
        timestamp = str(int(time.time()))
        random_uuid = str(uuid.uuid4())
        key_id_string = f"{timestamp}_{random_uuid}"
        import hashlib
        return hashlib.md5(key_id_string.encode()).hexdigest()[:16]
    
    @classmethod
    def generate_derive_key(cls, algorithm='AES-256'):
        """生成派生密钥（伪函数）"""
        import secrets
        # 根据算法生成不同长度的密钥
        key_lengths = {
            'AES-128': 16,
            'AES-192': 24,
            'AES-256': 32,
            'DES': 8,
            '3DES': 24,
        }
        length = key_lengths.get(algorithm, 32)
        key_bytes = secrets.token_bytes(length)
        return key_bytes.hex()
    
    @classmethod
    def generate_version(cls):
        """生成版本号"""
        timestamp = datetime.now().strftime("%Y%m%d%H%M%S")
        return f"v1.0.{timestamp}"
    
    def calculate_expires_at(self):
        """计算过期时间"""
        return self.created_at + timedelta(days=self.expiry_days)


class DeriveKeyAuditLog(models.Model):
    """派生密钥审计日志模型"""
    
    OPERATION_CHOICES = [
        ('create', 'create'),
        ('search', 'search'),
        ('disable', 'disable'),
        ('enable', 'enable'),
        ('update', 'update'),
        ('delete', 'delete'),
    ]
    
    id = models.AutoField(primary_key=True)
    key_id = models.CharField(max_length=64, verbose_name='密钥ID', db_index=True)
    operation = models.CharField(max_length=20, choices=OPERATION_CHOICES, verbose_name='操作类型', db_index=True)
    operation_time = models.DateTimeField(auto_now_add=True, verbose_name='操作时间', db_index=True)
    operator = models.CharField(max_length=64, verbose_name='操作者')
    ip_address = models.GenericIPAddressField(verbose_name='IP地址')
    user_agent = models.TextField(blank=True, verbose_name='用户代理')
    details = models.TextField(blank=True, verbose_name='操作详情')
    expired_at = models.DateTimeField(verbose_name='过期时间')
    
    class Meta:
        db_table = 'derive_key_audit_log'
        verbose_name = '派生密钥审计日志'
        verbose_name_plural = '派生密钥审计日志'
    
    def __str__(self):
        return f"{self.key_id} - {self.operation} - {self.operation_time}"
